package com.weaponlin.domain;

import sun.misc.Unsafe;

public class CustomAtomic {

    private volatile int value;

    private static final Unsafe unsafe = Unsafe.getUnsafe();
    private static final long valueOffset;

    static {
        try {
            valueOffset = unsafe.objectFieldOffset
                    (CustomAtomic.class.getDeclaredField("value"));
        } catch (Exception ex) {
            throw new Error(ex);
        }
    }

    public final int get() {
        return value;
    }

    public CustomAtomic() {
        this(0);
    }

    public CustomAtomic(int value) {
        this.value = value;
    }

    public final int simpleIncrementAndGet() {
        return ++value;
    }

    public final int incrementAndGet() {
        while (true) {
            int current = get();
            int next = current + 1;
            if (compareAndSet(current, next)) {
                return next;
            }
        }
    }

    private boolean compareAndSet(int current, int next) {
        return unsafe.compareAndSwapInt(this, valueOffset, current, next);
    }
}
